﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.IO;
using LeadExpress.Models.ViewPages;
using System.Data.SqlClient;
using System.Data;
using System.Web.Mvc;
using LeadExpress.Models;
using LeadExpress.Helpers;

namespace LeadExpress.Repository
{
    public class UserManagementRepository : BaseManagementRepository
    {
        #region Public Region
        public UserManagementModel GetModel(string pageType, string roleAdmin, string roleName, string keywords, string colName, string sortBy)
        {
            UserManagementModel model = new UserManagementModel();

            model.HeaderView = GetHeader();
            model.MenuItem = GetMenuItems(roleAdmin, pageType);

            // Calculate paging
            int pageSize = 10, pageIndex = 1, totalRecord = 0;
            model.ListUser = GetUserList(roleName, keywords, colName, sortBy, pageSize, pageIndex, ref totalRecord);

            if (totalRecord > 0)
            {
                PaginateModel paging = new PaginateModel();
                paging.PageIndex = pageIndex;
                paging.PageSize = pageSize;
                paging.TotalRecords = totalRecord;
                paging.TotalPages = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize + 1);

                model.Paging = paging;
            }

            return model;
        }

        public UserManagementModel GetModel(string roleName, string keywords, string colName, string sortBy, int pageSize, int pageIndex)
        {
            UserManagementModel model = new UserManagementModel();

            // Calculate paging
            int totalRecord = 0;
            model.ListUser = GetUserList(roleName, keywords, colName, sortBy, pageSize, pageIndex, ref totalRecord);
            PaginateModel paging = new PaginateModel();

            if (totalRecord > 0)
            {
                paging.PageIndex = pageIndex;
                paging.PageSize = pageSize;
                paging.TotalRecords = totalRecord;
                paging.TotalPages = (totalRecord % pageSize == 0) ? (totalRecord / pageSize) : (totalRecord / pageSize + 1);
            }
            else
            {
                paging.PageIndex = 1;
                paging.PageSize = 10;
                paging.TotalRecords = 0;
                paging.TotalPages = 1;
            }
            model.Paging = paging;

            return model;
        }

        public UserManagementModel GetModel(string pageType, string roleName, int id)
        {
            UserManagementModel model = new UserManagementModel();

            model.HeaderView = GetHeader();
            model.MenuItem = GetMenuItems(roleName, pageType);
            model.StateList = new Repository.StateRepository().GetAll();
            model.UserInfo = GetUserModel(id);

            return model;
        }

        public UserManagementModel GetModel(string pageType, string roleName)
        {
            UserManagementModel model = new UserManagementModel();

            model.HeaderView = GetHeader();
            model.MenuItem = GetMenuItems(roleName, pageType);
            model.StateList = new Repository.StateRepository().GetAll();

            return model;
        }

        public UserModel GetUserModel(int id)
        {
            UserModel model = new UserModel();

            var user = new LeadExpress.Repository.UserRepository().GetSingle(id);

            if (user != null)
            {
                model.ID = id;
                model.Fullname = user.Fullname;
                model.FirstName = user.FirstName;
                model.LastName = user.LastName;
                model.Email = user.Email;
                model.Address = user.Address;
                model.City = user.City;
                model.State = user.State;
                model.ZipCode = user.ZipCode;
                model.Phone = user.Phone;
                model.Mobile = user.Mobile;
                model.Fax = user.Fax;
                if (user.CreationDate != null)
                    model.CreationDate = Convert.ToDateTime(user.CreationDate).ToString("dd-MM-yyyy hh:mm tt");
                if (user.LastLoginDate != null)
                    model.LastLoginDate = Convert.ToDateTime(user.LastLoginDate).ToString("dd-MM-yyyy hh:mm tt");
                if (user.LastLockedOutDate != null)
                    model.LastLockedOutDate = Convert.ToDateTime(user.LastLockedOutDate).ToString("dd-MM-yyyy hh:mm tt");
                if (user.LastModified != null)
                    model.LastModified = Convert.ToDateTime(user.LastModified).ToString("dd-MM-yyyy hh:mm tt");
            }

            return model;
        }

        public UserInfo GetUserInfo(int id)
        {
            UserInfo model = new UserInfo();

            var user = new LeadExpress.Repository.UserRepository().GetSingle(id);

            if (user != null)
            {
                model.ID = id;
                model.Fullname = user.Fullname;
                model.FirstName = user.FirstName;
                model.LastName = user.LastName;
                model.Email = user.Email;
                model.Address = user.Address;
                model.City = user.City;
                model.State = user.State;
                model.ZipCode = user.ZipCode;
                model.Phone = user.Phone;
                model.Mobile = user.Mobile;
                model.Fax = user.Fax;
            }

            return model;
        }

        public FileResult ExportToCSVFile()
        {
            int totalRecord = 0;
            var list = GetUserList("ClientAdmin", "", "CreationDate", "desc", 1000000, 1, ref totalRecord);
            DataTable dt = CreateDataTableReturnLeads(list);
            return CreateCSVFile(dt, "UserReport");
        }
        #endregion

        #region Private Region

        private static DataTable CreateDataTableReturnLeads(List<UserInfo> data)
        {
            // Here we create a DataTable with columns.
            DataTable table = new DataTable();
            table.Columns.Add("Tên đầy đủ", typeof(string));
            table.Columns.Add("Ngày tạo", typeof(string));
            table.Columns.Add("Mã tài khoản", typeof(string));
            table.Columns.Add("Tên trước", typeof(string));
            table.Columns.Add("Tên sau", typeof(string));
            table.Columns.Add("Địa chỉ email", typeof(string));

            // Here we add DataRows.
            if (data.Count > 0)
            {
                foreach (var item in data)
                {
                    table.Rows.Add(item.Fullname, item.CreationDate, item.ID, item.FirstName, item.LastName, item.Email);
                }
            }
            return table;
        }


        private List<UserInfo> GetUserList(string roleName, string keywords, string colName, string sortBy, int pageSize, int pageIndex, ref int totalRecord)
        {
            EFRoleProvider provider = new EFRoleProvider();
            List<UserInfo> list = new List<UserInfo>();

            // Ref params
            SqlParameter paramRoleName = new SqlParameter("roleName", SqlDbType.NVarChar);
            SqlParameter paramKeyword = new SqlParameter("keywords", SqlDbType.NVarChar);
            SqlParameter paramColName = new SqlParameter("colName", SqlDbType.NVarChar);
            SqlParameter paramSortBy = new SqlParameter("sortBy", SqlDbType.NVarChar);
            paramRoleName.Value = roleName;
            paramKeyword.Value = keywords;
            paramColName.Value = colName;
            paramSortBy.Value = sortBy;

            // Execute a query
            using (SqlDataReader item = SqlHelper.ExecuteReader(SqlHelper.ConnectionStringProfile, CommandType.StoredProcedure, "GetAllUserByRole", paramRoleName, paramKeyword, paramColName, paramSortBy))
            {
                while (item.Read())
                {
                    UserInfo model = new UserInfo();

                    model.ID = item.GetInt32(0);
                    if (!item.IsDBNull(1))
                        model.Fullname = item.GetString(1);
                    if (!item.IsDBNull(2))
                        model.Email = item.GetString(2);
                    if (!item.IsDBNull(3))
                        model.Address = item.GetString(3);
                    if (!item.IsDBNull(4))
                        model.City = item.GetString(4);
                    if (!item.IsDBNull(5))
                        model.State = item.GetString(5);
                    if (!item.IsDBNull(6))
                        model.ZipCode = item.GetString(6);
                    if (!item.IsDBNull(7))
                        model.Phone = item.GetString(7);
                    if (!item.IsDBNull(8))
                        model.Mobile = item.GetString(8);
                    if (!item.IsDBNull(9))
                        model.Fax = item.GetString(9);
                    if (!item.IsDBNull(10))
                        model.CreationDate = item.GetDateTime(10).ToString("dd-MM-yyyy hh:mm tt");
                    if (!item.IsDBNull(11))
                        model.NumLogin = item.GetInt32(11);
                    if (!item.IsDBNull(12))
                        model.IsApproved = item.GetBoolean(12);
                    if (!item.IsDBNull(13))
                        model.IsLockedOut = item.GetBoolean(13);
                    if (!item.IsDBNull(14))
                        model.Active = item.GetBoolean(14);

                    model.Status = (model.IsLockedOut) ? "Khóa" : "Mở";

                    if (!string.IsNullOrEmpty(model.State))
                    {
                        var state = new StateRepository().GetSingle(model.State);
                        if (state != null)
                            model.State = state.Name;
                    }

                    model.RoleName = roleName;
                    
                    list.Add(model);
                }
            }

            totalRecord = list.Count;

            return list.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        #endregion
    }
}